package icu.ac.kr.phonebook.activity;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import network.NetworkModule;

import icu.ac.kr.phonebook.R;
import icu.ac.kr.phonebook.provider.PacelableObject;
import icu.ac.kr.phonebook.provider.ReservedWork;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class SeachScheduleActivity extends Activity {

	static String date, month, year;
	HashMap <Integer, String> contactHash;
	Handler handler = new Handler();
	static final String TAG = "SeachScheduleActivity";
	NetworkModule network;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	
		setContentView(R.layout.searchschedule);
	
		Spinner spin = (Spinner) findViewById(R.id.datespin);
		spin.setPrompt("Choose date");
		ArrayAdapter<CharSequence> adspin;
		
		adspin = ArrayAdapter.createFromResource(this,R.array.date, android.R.layout.simple_spinner_item);
		spin.setAdapter(adspin);
		spin.setOnItemSelectedListener(mListener);
		
		spin = (Spinner) findViewById(R.id.monthspin);
		spin.setPrompt("Choose month");
		adspin = ArrayAdapter.createFromResource(this,R.array.month, android.R.layout.simple_spinner_item);
		spin.setAdapter(adspin);
		spin.setOnItemSelectedListener(mListener);
		spin = (Spinner) findViewById(R.id.yearspin);
		spin.setPrompt("Choose year");
		adspin = ArrayAdapter.createFromResource(this,R.array.year, android.R.layout.simple_spinner_item);
		spin.setAdapter(adspin);
	 	spin.setOnItemSelectedListener(mListener);
		
	 	ListView list = (ListView) findViewById(R.id.contactlist);
	 	 Cursor c = getContentResolver().query(Data.CONTENT_URI, 
	              new String[]{Phone._ID, Phone.DATA1, Phone.DATA2}, 
	                "DATA2 == 2", 
	                null, null); 
	 	ContactAdapter contactAdapter = new ContactAdapter(this, c);
	 	list.setAdapter(contactAdapter);
	 	list.setOnItemClickListener(new OnItemClickListener(){
	 		
			public void onItemClick(AdapterView<?> data, View arg1, int position,
					long id) {
				// TODO Auto-generated method stub
				
				conntectToServer(position);
				
				
			}
	 		
	 	});
	 	
	}
	
	private void conntectToServer(int position)
	{
	
		network = new NetworkModule(this, handler);
		network.connectToServer(Integer.parseInt(contactHash.get(position)),"none", "GET");
		String remoteIp = network.getRemoteIp();
		Log.d(TAG, "Remote Client server : " + remoteIp);
		connectToRemoteTerminal(remoteIp);
		
	}
	
	private void connectToRemoteTerminal(String ip)
	{
	
		String schedule = network.connectToTerminal(date, month, year, ip);
		Intent intent = new Intent(SeachScheduleActivity.this, ViewSchedule.class);
		
		HashMap<Integer, ReservedWork> reserved = new HashMap<Integer, ReservedWork>();
		HashMap <Integer, ReservedWork> scheduled = new HashMap<Integer, ReservedWork>();

		try {
			Log.d(TAG, schedule);
			JSONArray json = new JSONArray(schedule);
			Log.d(TAG, "Length : "+ json.length());

			for (int i = 0; i < json.length(); i++)
			{
				
				JSONObject obj = json.getJSONObject(i);
								
				scheduled.put(new Integer(obj.getInt("hour")), 
						new ReservedWork( Integer.parseInt(obj.getString("hour")),
								obj.getString("type"),
								obj.getString("comment"),
								 obj.getInt("mode"))
					);		
				
			}
			
		
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Bundle bundle = new Bundle();
	 	bundle.putParcelableArray("schedule", new PacelableObject[]{new PacelableObject(reserved), new PacelableObject(scheduled)});

		bundle.putString("year", year);
		bundle.putString("month", month);
		bundle.putString("date", date); 
		bundle.putInt("mode", 0);
		bundle.putString("from", "SearchSchedule");
	 	intent.putExtras(bundle);
		startActivity(intent);
	}
	
	private class ContactAdapter extends CursorAdapter{

		int count;
		public ContactAdapter(Context context, Cursor c) {
			super(context, c);
			// TODO Auto-generated constructor stub
			contactHash = new HashMap<Integer, String>();
			count = 0;
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			// TODO Auto-generated method stub
			
			if (cursor.getInt(cursor.getColumnIndex(Phone.TYPE)) == Phone.TYPE_MOBILE)
			{
				TextView phonenumber = (TextView) view.findViewById(R.id.phonenumber);
				phonenumber.setText(cursor.getString(cursor.getColumnIndex(Phone.NUMBER)));
				contactHash.put(new Integer(count++), cursor.getString(cursor.getColumnIndex(Phone.NUMBER)));
			}
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			// TODO Auto-generated method stub
			LayoutInflater inflater = LayoutInflater.from(context);
			View view = inflater.inflate(R.layout.contactlist, null);
			
			return view;
		}
		
		
	}
	

	Spinner.OnItemSelectedListener mListener = new Spinner.OnItemSelectedListener(){

		public void onItemSelected(AdapterView<?> data, View view, int position,
				long arg3) {
			// TODO Auto-generated method stub
			
			switch(data.getId())
			{
			case R.id.datespin:
				date = data.getSelectedItem().toString();
			 	break;
			case R.id.monthspin:
				month =  ""+(position+1);  //data.getSelectedItem().toString();
				break;
			case R.id.yearspin:
				year = data.getSelectedItem().toString();
				break;
			}
			
		}

		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
		
	};
	
	
	
}
